package com.jianggujin.zkgui;

import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

public class ConfigItemChooserDialog extends JDialog {
    private JTable configTable;
    private DefaultTableModel configTableModel;
    private JButton connectBtn;
    private JButton addBtn;
    private JButton updateBtn;
    private JButton removeBtn;
    private JButton copyBtn;
    private JButton closeBtn;
    private MainFrame mainFrame;

    private ConfigItemChooserDialog(MainFrame mainFrame) {
        super(mainFrame);
        this.mainFrame = mainFrame;
        initComponent();
        initDialog();
    }

    private void initComponent() {
        List<ConfigItem> configItems = ConfigStore.loadConfig();
        configTableModel = new DefaultTableModel(new String[] { "名称", "地址", "空间" }, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        if (configItems != null) {
            configItems.forEach(item -> {
                configTableModel.addRow(new Object[] { item.getName(), item.getConnectString(), item.getNamespace() });
            });
        }
        configTable = new JTable(configTableModel);
        configTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        configTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
                    int index = configTable.getSelectedRow();
                    if (index < 0 || index >= configTable.getRowCount()) {
                        return;
                    }
                    dispose();
                    mainFrame.connect(getConfigItem(index));
                }
            }
        });

        this.add(new JScrollPane(configTable));

        Box east = Box.createVerticalBox();
        connectBtn = new JButton("连接");
        connectBtn.addActionListener(e -> {
            int index = configTable.getSelectedRow();
            if (index < 0 || index >= configTable.getRowCount()) {
                JOptionPane.showMessageDialog(this, "请先选择需要连接的数据");
                return;
            }
            dispose();
            mainFrame.connect(getConfigItem(index));
        });
        east.add(connectBtn);

        addBtn = new JButton("添加");
        addBtn.addActionListener(e -> ConfigItemDialog.showAddDialog(this));
        east.add(addBtn);

        updateBtn = new JButton("修改");
        updateBtn.addActionListener(e -> {
            int index = configTable.getSelectedRow();
            if (index < 0 || index >= configTable.getRowCount()) {
                JOptionPane.showMessageDialog(this, "请先选择需要修改的数据");
                return;
            }
            ConfigItemDialog.showUpdateDialog(this, index, getConfigItem(index));
        });
        east.add(updateBtn);

        copyBtn = new JButton("复制");
        copyBtn.addActionListener(e -> {
            int index = configTable.getSelectedRow();
            if (index < 0 || index >= configTable.getRowCount()) {
                JOptionPane.showMessageDialog(this, "请先选择需要复制的数据");
                return;
            }
            ConfigItem item = getConfigItem(index);
            configTableModel.addRow(new Object[] { item.getName(), item.getConnectString(), item.getNamespace() });
            saveConfig();
        });
        east.add(copyBtn);

        removeBtn = new JButton("删除");
        removeBtn.addActionListener(e -> {
            int index = configTable.getSelectedRow();
            if (index < 0 || index >= configTable.getRowCount()) {
                JOptionPane.showMessageDialog(this, "请先选择需要删除的数据");
                return;
            }
            configTableModel.removeRow(index);
            saveConfig();
        });
        east.add(removeBtn);

        closeBtn = new JButton("关闭");
        closeBtn.addActionListener(e -> dispose());
        east.add(closeBtn);
        this.add(east, BorderLayout.EAST);
    }

    private ConfigItem getConfigItem(int row) {
        ConfigItem item = new ConfigItem();
        item.setName(configTableModel.getValueAt(row, 0).toString());
        item.setConnectString(configTableModel.getValueAt(row, 1).toString());
        Object namespace = configTableModel.getValueAt(row, 2);
        if (namespace != null) {
            item.setNamespace(namespace.toString());
        }
        return item;
    }

    private void saveConfig() {
        List<ConfigItem> tmp = new ArrayList<>();
        int count = configTable.getRowCount();
        for (int i = 0; i < count; i++) {
            tmp.add(getConfigItem(i));
        }
        ConfigStore.saveConfig(tmp);
    }

    private void initDialog() {
        setTitle("选择连接");
        setModal(true);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setSize(400, 300);
        int width = Toolkit.getDefaultToolkit().getScreenSize().width;
        int height = Toolkit.getDefaultToolkit().getScreenSize().height;
        // 设置窗体在显示器居中显示
        this.setBounds((width - getWidth()) / 2, (height - getHeight()) / 2, getWidth(), getHeight());
        this.setVisible(true);
    }

    public void addConfigItem(ConfigItem item) {
        configTableModel.addRow(new Object[] { item.getName(), item.getConnectString(), item.getNamespace() });
        this.saveConfig();
    }

    public void updateConfigItem(int row, ConfigItem item) {
        configTableModel.setValueAt(item.getName(), row, 0);
        configTableModel.setValueAt(item.getConnectString(), row, 1);
        configTableModel.setValueAt(item.getNamespace(), row, 2);
        this.saveConfig();
    }

    public static void showChooser(MainFrame mainFrame) {
        new ConfigItemChooserDialog(mainFrame);
    }
}
